package com.cuanbo.dualscreenteachzhu.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.cuanbo.dualscreenteachzhu.R;
import com.cuanbo.dualscreenteachzhu.activity.MainActivity;
import com.cuanbo.dualscreenteachzhu.base.App;
import com.cuanbo.dualscreenteachzhu.bean.DrawBoradPage;
import com.cuanbo.dualscreenteachzhu.bean.EventBusBean;
import com.cuanbo.dualscreenteachzhu.bean.MyPath;
import com.cuanbo.dualscreenteachzhu.bean.Point;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 *画板
 */
public class DrawBoard extends androidx.appcompat.widget.AppCompatImageView {
    public static int width;
    public static int height;
    private Paint paint;
    private int color=0xffff0000;
    public static float strokeWidth=2f;
    public static float clearStrokeWidth=100f;
    private boolean isClear;
    private List<Point> pointList;
    private List<DrawBoradPage> pages=new ArrayList<>();
    private int type=0;
    private boolean isTouch;

    public DrawBoard(Context context) {
        this(context, null);
    }

    public DrawBoard(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DrawBoard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        paint = new Paint();
        paint.setColor(color);
        paint.setStrokeWidth(strokeWidth);
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);
        DrawBoradPage page=new DrawBoradPage();
        page.setCheck(true);
        List<MyPath> lines=new ArrayList<>();
        page.setLines(lines);
        pages.add(page);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int count=canvas.saveLayer(0,0,width,height,paint,Canvas.ALL_SAVE_FLAG);

        for (int i = 0; i< getNowPaths().size(); i++){
            MyPath myPath= getNowPaths().get(i);
            Path path=new Path();
            for (int j=0;j<myPath.getPointList().size();j++){
                Point p=myPath.getPointList().get(j);
                if(j==0) {
                    path.moveTo(p.getX(), p.getY());
                }else{
                    Point p0=myPath.getPointList().get(j-1);
                    path.quadTo(p0.getX(), p0.getY(),p.getX(), p.getY());
                }
            }

            paint.setColor(myPath.getColor());
            paint.setStrokeWidth(myPath.getStrokeWidth());
            if(myPath.isClear()){
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
                canvas.drawPath(path,paint);
                paint.setXfermode(null);
            }else{
                if(myPath.getType()==MyPath.PATH){
                    canvas.drawPath(path,paint);
                }else if(myPath.getType()==MyPath.CIRCLE){
                    if(myPath.getPointList().size()>=2){
                        Point p0=myPath.getPointList().get(0);
                        Point p1=myPath.getPointList().get(myPath.getPointList().size()-1);
                        float offsetX=(p1.getX()-p0.getX())/2;
                        float offsetY=(p1.getY()-p0.getY())/2;
                        float x=offsetX+p0.getX();
                        float y=offsetY+p0.getY();
                        float r=offsetX;
                        if(offsetX<offsetY){
                            r=offsetY;
                        }
                        canvas.drawCircle(x,y,r,paint);
                    }
                }else if(myPath.getType()==MyPath.RECT){
                    if(myPath.getPointList().size()>=2){
                        Point p0=myPath.getPointList().get(0);
                        Point p1=myPath.getPointList().get(myPath.getPointList().size()-1);
                        float left=p0.getX()<p1.getX()?p0.getX():p1.getX();
                        float top=p0.getY()<p1.getY()?p0.getY():p1.getY();
                        float right=p0.getX()>p1.getX()?p0.getX():p1.getX();
                        float bottom=p0.getY()>p1.getY()?p0.getY():p1.getY();
                        canvas.drawRect(left,top,right,bottom,paint);
                    }
                }else if(myPath.getType()==MyPath.LINE){
                    Point p0=myPath.getPointList().get(0);
                    Point p1=myPath.getPointList().get(myPath.getPointList().size()-1);
                    canvas.drawLine(p0.getX(),p0.getY(),p1.getX(),p1.getY(),paint);
                }else if(myPath.getType()==MyPath.TRIANGLE){
                    Point p0=myPath.getPointList().get(0);
                    Point p1=myPath.getPointList().get(myPath.getPointList().size()-1);
                }
            }
        }
        if(isClear&&isTouch){
            paint.setColor(0xff999999);
            paint.setStrokeWidth(2f);
            paint.setStyle(Paint.Style.STROKE);
            paint.setAntiAlias(true);
            canvas.drawRect(eraserPointerX-25,eraserPointerY-25,eraserPointerX+25,eraserPointerY+25,paint);
        }
        canvas.restoreToCount(count);
    }

    float eraserPointerX=0;
    float eraserPointerY=0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()== MotionEvent.ACTION_DOWN){
            isTouch=true;
            EventBus.getDefault().post(new EventBusBean(EventBusBean.DRAWBOARD_TOUCH));
            pointList=new ArrayList<>();
            MyPath myPath=null;
            if(isClear){
                myPath=new MyPath(type,color,clearStrokeWidth,isClear,pointList);
            }else{
                myPath=new MyPath(type,color,strokeWidth,isClear,pointList);
            }
            getNowPaths().add(myPath);
            pointList.add(new Point(event.getX(),event.getY()));
            eraserPointerX=event.getX();
            eraserPointerY=event.getY();
        }else if(event.getAction()== MotionEvent.ACTION_MOVE){
            pointList.add(new Point(event.getX(),event.getY()));
            eraserPointerX=event.getX();
            eraserPointerY=event.getY();
        }else if(event.getAction()== MotionEvent.ACTION_UP){
            isTouch=false;
        }
        invalidate();
        return true;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    public void clearDrawBoard(){
        invalidate();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(EventBusBean eventBusBean) {
        if(eventBusBean.getType()== EventBusBean.BUTTON_COMMENTS_NO){
            removeNowPagePaths();
            EventBusBean ebb=new EventBusBean(EventBusBean.DRAWBOARD_PAGE);
            ebb.setData(pages);
            EventBus.getDefault().post(ebb);
        }else if(eventBusBean.getType()== EventBusBean.BUTTON_COMMENTS_OFF){
            clearDrawBoard();
            setVisibility(View.GONE);
            /*File f=new File(App.capturePath+App.captureFileName);
            if(f.exists()){
                f.delete();
            }*/
        }else if(eventBusBean.getType()== EventBusBean.MODE_WHITE_BOARD){
            setBackgroundColor(0xff0e490a);
            setAlpha(0);
            setVisibility(View.VISIBLE);
        }else if(eventBusBean.getType()== EventBusBean.MODE_COMMENT){
            if(MainActivity.isCompare){
                setBackgroundColor(0x00000000);
                setAlpha(0);
                setVisibility(View.VISIBLE);
            }else{
                setBackgroundColor(0x00000000);
                setAlpha(255);
                Glide.with(this).load(App.commentPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(this);
            }
            setVisibility(View.VISIBLE);
        }else if(eventBusBean.getType()== EventBusBean.ERASER){
            isClear=true;
        }else if(eventBusBean.getType()== EventBusBean.PEN){
            isClear=false;
            type=MyPath.PATH;
        }else if(eventBusBean.getType()== EventBusBean.RECT){
            isClear=false;
            type=MyPath.RECT;
        }else if(eventBusBean.getType()== EventBusBean.LINE){
            isClear=false;
            type=MyPath.LINE;
        }else if(eventBusBean.getType()== EventBusBean.TRIANGLE){
            isClear=false;
            type=MyPath.TRIANGLE;
        }else if(eventBusBean.getType()== EventBusBean.RETRACT){
            retractNowPath();
            invalidate();
        }else if(eventBusBean.getType()== EventBusBean.NORETRACT){
            noRetractNowPath();
            invalidate();
        }else if(eventBusBean.getType()== EventBusBean.CIRCLE){
            isClear=false;
            type=MyPath.CIRCLE;
        }else if(eventBusBean.getType()== EventBusBean.DRAWBOARD){

        }else if(eventBusBean.getType()== EventBusBean.DRAWBOARD_PAGE){
            clearAllRetractLines();
            invalidate();
        }else if(eventBusBean.getType()== EventBusBean.DRAWBOARD_CLEAR){
            removeNowPagePaths();
            invalidate();
        }else if(eventBusBean.getType()== EventBusBean.DRAWBOARD_SEEKBAR){
            int progress=(int)eventBusBean.getData();
            if(isClear){
                clearStrokeWidth=progress*2;
            }else{
                strokeWidth=progress/4;
            }
        }else if(eventBusBean.getType()== EventBusBean.UPDATE_DRAWBOARD_PARAMETER){
            int id= (int) eventBusBean.getData();
            if(id== R.id.vC1){
                color=0xffe34a4e;
            }else if(id== R.id.vC2){
                color=0xff000000;
            }else if(id== R.id.vC3){
                color=0xffffffff;
            }else if(id== R.id.vC4){
                color=0xff00FF40;
            }else if(id== R.id.vC5){
                color=0xffFFF000;
            }else if(id== R.id.vC6){
                color=0xff0080FF;
            }else if(id== R.id.ivPen){
                strokeWidth=2f;
            }else if(id== R.id.ivXpc){
                isClear=true;
                clearStrokeWidth=40;
            }
        }
    }

    public List<MyPath> getNowPaths(){
        for (int i=0;i<pages.size();i++){
            DrawBoradPage page=pages.get(i);
            if(page.isCheck()){
                return page.getLines();
            }
        }
        return new ArrayList<>();
    }

    public void removeNowPagePaths(){
        List<MyPath> lines= getNowPaths();
        lines.removeAll(lines);
    }

    private List<MyPath> retractLines=new ArrayList<>();

    public void retractNowPath(){
        List<MyPath> lines= getNowPaths();
        if(lines.size()<=0)return;
        MyPath myPath=lines.get(lines.size()-1);
        retractLines.add(myPath);
        lines.remove(myPath);
    }

    public void noRetractNowPath(){
        if(retractLines.size()<=0)return;
        MyPath myPath=retractLines.get(retractLines.size()-1);
        retractLines.remove(myPath);
        getNowPaths().add(myPath);
    }

    public void clearAllRetractLines(){
        retractLines.removeAll(retractLines);
    }

}
